<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>leenty blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="leenty 不会捣(xia)鼓(gao)的前端不是好全栈">
<meta name="keywords" content="前端,vuejs,vue-router,vuex,vue-cli,javascript,js,mvvm,css3,html5,git,github">
<meta property="og:type" content="website">
<meta property="og:title" content="leenty blog">
<meta property="og:url" content="http://baidu.com/index.html">
<meta property="og:site_name" content="leenty blog">
<meta property="og:description" content="leenty 不会捣(xia)鼓(gao)的前端不是好全栈">
<meta property="og:locale" content="zh-CN">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="leenty blog">
<meta name="twitter:description" content="leenty 不会捣(xia)鼓(gao)的前端不是好全栈">
  
    <link rel="alternative" href="/atom.xml" title="leenty blog" type="application/atom+xml">
  
  
    <link rel="icon" href="//favicon.png">
  
  <script src="/style.js"></script>
  

  
<!-- baidu_tongji -->
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?5bae4c35e53fde3bf2526312c3edaf1d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
<!-- End baidu_tongji -->


</head>
</html>
<body>
  <div id="container">
    <div class="left-col">
      <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img src="/img/default_avatar.png" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">leenty</a></h1>
		</hgroup>

		

		<nav class="header-menu">
			<ul>
			
				<li><a href="/">主页</a></li>
	        
				<li><a href="/archives">所有文章</a></li>
	        
			</ul>
		</nav>
		<nav class="header-smart-menu">
	        
    		
    			
    			<a class="js-smart-menu" data-idx="0" href="javascript:void(0)">所有文章</a>
    			
    			
            
    			
    			<a class="js-smart-menu" data-idx="1" href="javascript:void(0)">标签</a>
    			
    			
            
    			
    			<a class="js-smart-menu" data-idx="2" href="javascript:void(0)">友链</a>
    			
    			
            
    			
    			<a class="js-smart-menu" data-idx="3" href="javascript:void(0)">关于我</a>
    			
    			
            
		</nav>
		<nav class="header-nav">
			<div class="social">
				
					<a class="github" target="_blank" href="https://github.com/leenty" title="github">github</a>
		        
			</div>
		</nav>
	</header>		
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"><i class="icon-list"></i></div>
  		<h1 class="header-author js-mobile-header hide">leenty</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				
					<img src="/img/default_avatar.png" class="js-avatar">
				
			</div>
			<hgroup>
			  <h1 class="header-author">leenty</h1>
			</hgroup>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">主页</a></li>
		        
					<li><a href="/archives">所有文章</a></li>
		        
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="https://github.com/leenty" title="github">github</a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div class="body-wrap">
        
  
    <article id="post-vue2-6" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/12/18/vue2-6/">vue2.0一起在懵逼的海洋里越陷越深（六）</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>本文章系列：<a href="http://leenty.com/tags/vuejs/" target="_blank" rel="noopener">vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)</a><br><a href="http://vue2.leenty.com" target="_blank" rel="noopener">演示场地vue2.0 Demo</a>,这是<a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">源码地址</a>,觉得靠谱的话欢迎加星跟随,有问题欢迎评论和指正😃</p>
<p>在vue开发SPA应用的过程中，多数情况下我们需要解决一个问题<br>就是在路由跳转的过程中需要更新你SPA应用的<code>title</code> ，<br>这一节不说其他，就展示如何使用<code>vue-router</code>的<strong>导航钩子</strong>去解决这么一个问题。<br>接下来就愉快的去玩耍啦！<br><img src="http://www.leenty.com/img/vue/huaji_ld.jpg" alt="红红火火恍恍惚惚"></p>
<h3 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h3><p>好的，介绍下背景，我有这么一个<a href="http://vue2.leenty.com" target="_blank" rel="noopener">博客的demo</a>，里面有多个版块，每个版块有着不同的名称(<code>title</code>)<br>先看一下Demo的路由结构<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">vue2.leenty.com</span><br><span class="line">├── home                # 首页版块</span><br><span class="line">├── article             # 文章版块</span><br><span class="line">│   ├── vue2-1            # 具体文章一</span><br><span class="line">│   ├── vue2-2            # 具体文章二</span><br><span class="line">│   ├── vue2-3            # 具体文章三</span><br><span class="line">│   ├── vue2-4            # 具体文章四</span><br><span class="line">│   ├── vue2-5            # 具体文章五</span><br><span class="line">│   └── vue2-6            # 具体文章六</span><br><span class="line">└── demo                # 演示版块</span><br><span class="line">    └── demo-1            # 具体演示一</span><br></pre></td></tr></table></figure></p>
<p>好的，接下来要实现的是在切换路由的时候同时的去切换你页面的<code>title</code></p>
<h4 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h4><p>这里思路是使用<code>vue-router</code>的路由全局导航钩子去解决这个问题<br>在路由对象里添加一个<code>title</code>字段以供路由全局导航钩子读取并更新页面<code>title</code></p>
<h4 id="配置路由"><a href="#配置路由" class="headerlink" title="配置路由"></a>配置路由</h4><p>所以第一步，先在路由对象里添加这一个字段。<br>打开<code>src/routes.js</code>(<a href="https://github.com/leenty/vue2/blob/master/src/routes.js" target="_blank" rel="noopener">源文件地址：https://github.com/leenty/vue2/blob/master/src/routes.js</a>)<br><strong>（注意是<code>routes.js</code>,这是咱用来存放路由对象的文件）</strong><br>在原有数据的基础上添加<code>title</code><br>这里其实vue1.0和vue2.0的实现是差不多的，所以vue1.0也是可以使用的。<br>vue2.0路由对象提供了一个<code>meta</code>字段来给你存放一些其他信息，所以这里就可以用来存放<code>title</code><br>vue1.0的话是没有这个字段的，所以可以直接与<code>path</code>平级。<br>具体如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> routes = [</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Home'</span>,</span><br><span class="line">    path: <span class="string">'/'</span>,</span><br><span class="line">    meta: &#123;</span><br><span class="line">      title: <span class="string">'home'</span> <span class="comment">// 主页的title为home</span></span><br><span class="line">    &#125;,</span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Home.vue'</span>)</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Article'</span>,</span><br><span class="line">    path: <span class="string">'/article'</span>,</span><br><span class="line">    meta: &#123;</span><br><span class="line">      title: <span class="string">'article'</span> <span class="comment">// 文章模块相应的title为article</span></span><br><span class="line">    &#125;,</span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Article.vue'</span>),</span><br><span class="line">    children: [</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'vue2_1'</span>,</span><br><span class="line">        path: <span class="string">'/article/vue2_1'</span>,</span><br><span class="line">        meta: &#123;</span><br><span class="line">          title: <span class="string">'vue2.0一起在懵逼的海洋里越陷越深（一）'</span> <span class="comment">// 子路由也是一样的道理</span></span><br><span class="line">        &#125;,</span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./md/articles/vue2-1.md'</span>)</span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="comment">// ... 子路由和父路由都差不多，所以后面的就省略了</span></span><br><span class="line">    ]</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Demo'</span>,</span><br><span class="line">    path: <span class="string">'/demo'</span>,</span><br><span class="line">    meta: &#123;</span><br><span class="line">      title: <span class="string">'demo'</span> <span class="comment">// 演示模块title为demo</span></span><br><span class="line">    &#125;,</span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Demo.vue'</span>),</span><br><span class="line">    children: [</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'DemoVuexState'</span>,</span><br><span class="line">        path: <span class="string">'vuex_state'</span>,</span><br><span class="line">        meta: &#123;</span><br><span class="line">          title: <span class="string">'vuex演示'</span></span><br><span class="line">        &#125;,</span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./components/DemoVuexState.vue'</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> routes</span><br></pre></td></tr></table></figure></p>
<p>如此这般，各个页面的<code>title</code>就预设好了</p>
<p>小明：”为什么<code>title</code>里不加上站点名后缀？像<code>demo - leenty blog</code>这样？“<br>老师：“滚出去！”</p>
<p>其实是这样的，后缀如果一个个加也是可以的，但为什么不用语句帮我们加上去呢？<br>这样就一劳永逸啦，再也不用自己一个个打后缀了，哈哈哈，真TM机智！<br><img src="http://www.leenty.com/img/vue/mdzz.jpg" alt="mdzz"></p>
<h4 id="路由导航钩子介绍"><a href="#路由导航钩子介绍" class="headerlink" title="路由导航钩子介绍"></a>路由导航钩子介绍</h4><p>讲一讲这个所谓的全局导航钩子，听起来玄不愣登的。。。</p>
<p>导航是发生在路由改变时的事件，这也是为何网页的导航条叫导航条的原因<br>尤大大的原话是：“正如其名，vue-router 提供的导航钩子主要用来拦截导航，让它完成跳转或取消。有多种方式可以在路由导航发生时执行钩子：全局的, 单个路由独享的, 或者组件级的”<br>说的很明白，言简意赅，其实就是能让你控制导航的一个方法而已<br>导航钩子分为全局，单个路由独享和组件级别的。<br>但不论如何，导航钩子都接受一个函数为参数，并会在导航过程中调用这个函数。<br>函数会被传入3个参数，分别为<code>to, from, next</code><br>没错，你看字面意思应该理解了个大概，即：<br><code>from</code>：你从哪里来？(问询消息的小弟A)<br><code>to</code>：要到哪里去？(问询消息的小弟B)<br><code>next</code>：让不让过去还得看老子我的！(大哥你懂不)</p>
<p>上面这位大哥(<code>next</code>)会有三中方法！<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">next() <span class="comment">// 默认通过路由</span></span><br><span class="line">next(<span class="literal">false</span>) <span class="comment">// 中止导航，那么将会跳回到from的地址</span></span><br><span class="line">next(&#123; <span class="attr">path</span>: <span class="string">'/'</span> &#125;) <span class="comment">// 跟一个路由参数对象，将会中止当前导航并跳往指向的路由</span></span><br></pre></td></tr></table></figure></p>
<p>好的，先看看全局的写法<br><strong>全局导航钩子</strong>一共两个，<code>router.beforeEach</code>和<code>router.afterEach</code><br>一个触发于导航开始前，一个触发于导航开始后。用法呢，都是一样的，如下！<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123; ... &#125;)</span><br><span class="line"></span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">  next(<span class="literal">false</span>) <span class="comment">// 大哥：谁让你过去的？</span></span><br><span class="line">  <span class="comment">// 调用next(false)中止导航，于是页面回到跳转前</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">router.afterEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">  next() <span class="comment">// 大哥：过去吧！</span></span><br><span class="line">  <span class="comment">// 调用next通过路由</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="string">``</span></span><br><span class="line"></span><br><span class="line">**单个路由独享的钩子**，同样是两个方法<span class="string">`beforeEnter`</span>和<span class="string">`afterEnter`</span>，同样的套路。</span><br><span class="line">套路如下：</span><br><span class="line"><span class="string">``</span><span class="string">`js</span></span><br><span class="line"><span class="string">const router = new VueRouter(&#123;</span></span><br><span class="line"><span class="string">  routes: [</span></span><br><span class="line"><span class="string">    &#123;</span></span><br><span class="line"><span class="string">      path: '/demo',</span></span><br><span class="line"><span class="string">      component: Demo,</span></span><br><span class="line"><span class="string">      beforeEnter: (to, from, next) =&gt; &#123;</span></span><br><span class="line"><span class="string">        console.log('小弟B：哎呀妈呀！大兄弟，这是要去哪呀？', to)</span></span><br><span class="line"><span class="string">        console.log('小弟A：大兄弟，哪儿旮沓的呀！', from)</span></span><br><span class="line"><span class="string">        next() // 大哥：过去吧！</span></span><br><span class="line"><span class="string">        // 调用next通过路由</span></span><br><span class="line"><span class="string">      &#125;,</span></span><br><span class="line"><span class="string">      afterEnter: (to, from, next) =&gt; &#123;</span></span><br><span class="line"><span class="string">        console.log('小弟B：哎呀妈呀！大兄弟，这是要去哪呀？', to)</span></span><br><span class="line"><span class="string">        console.log('小弟A：大兄弟，哪儿旮沓的呀！', from)</span></span><br><span class="line"><span class="string">        next(&#123; path: '/' &#125;) // 大哥：像那边走！</span></span><br><span class="line"><span class="string">        // 调用next(&#123; path: '/' &#125;)中止导航，并跳到首页</span></span><br><span class="line"><span class="string">      &#125;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">  ]</span></span><br><span class="line"><span class="string">&#125;)</span></span><br></pre></td></tr></table></figure></p>
<p><strong>组件内的钩子</strong>，依然是一对基友方法<code>beforeRouteEnter</code>和<code>beforeRouteLeave</code><br>套路还是一样的0.0<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Demo = &#123;</span><br><span class="line">  template: <span class="string">`&lt;div&gt;this is a Demo &lt;/div&gt;`</span>,</span><br><span class="line">  beforeRouteEnter (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">    next() <span class="comment">// 大哥：过去吧！</span></span><br><span class="line">    <span class="comment">// 在渲染该组件的对应路由被 confirm 前调用</span></span><br><span class="line">    <span class="comment">// 不！能！获取组件实例 `this`</span></span><br><span class="line">    <span class="comment">// 因为当钩子执行前，组件实例还没被创建</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeRouteLeave (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">    next() <span class="comment">// 大哥：过去吧！</span></span><br><span class="line">    <span class="comment">// 导航离开该组件的对应路由时调用</span></span><br><span class="line">    <span class="comment">// 可以访问组件实例 `this`</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="配合路由全局导航钩子去更新title"><a href="#配合路由全局导航钩子去更新title" class="headerlink" title="配合路由全局导航钩子去更新title"></a>配合路由全局导航钩子去更新<code>title</code></h4><p>好的，三种都介绍完了，那么打开<code>src/router.js</code>，没错，这回是<code>router.js</code>，这是咱装载路由的文件</p>
<p>在此之前，我们还需要知道在一个嵌套路由情况下的节点分布。<br>三个参数之一的<code>to</code>存在属性<code>to.matched</code>,里面存在了一个包含路由节点的数组<br>顺序是从子路由到根路由</p>
<p>好的，确定下title文案</p>
<table>
<thead>
<tr>
<th style="text-align:left">router</th>
<th style="text-align:center">title</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left"><code>├── home</code></td>
<td style="text-align:center">leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>├── article</code></td>
<td style="text-align:center">article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>│   ├── vue2-1</code></td>
<td style="text-align:center">vue2.0一起在懵逼的海洋里越陷越深（一） - article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>│   ├── ...</code></td>
<td style="text-align:center">… - article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>│   └── vue2-6</code></td>
<td style="text-align:center">vue2.0一起在懵逼的海洋里越陷越深（六） - article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>└── demo</code></td>
<td style="text-align:center">demo - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>└── demo-1</code></td>
<td style="text-align:center">具体演示1 - demo - leenty blog</td>
</tr>
</tbody>
</table>
<p>里面的结构是这样的<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> VueRouter <span class="keyword">from</span> <span class="string">'vue-router'</span></span><br><span class="line"><span class="keyword">import</span> routes <span class="keyword">from</span> <span class="string">'./routes'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> title = <span class="string">'leenty blog'</span></span><br><span class="line"><span class="comment">// 定义我们站点的名字</span></span><br><span class="line"></span><br><span class="line">Vue.use(VueRouter)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* eslint-disable no-new */</span></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  mode: <span class="string">'history'</span>,</span><br><span class="line">  linkActiveClass: <span class="string">'u-link--Active'</span>,</span><br><span class="line">  routes</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 路由导航钩子，beforeEach，在路由进入前调用</span></span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> titleStr = <span class="string">''</span></span><br><span class="line">  <span class="comment">// 检测是不是要跳转首页，如果是，则不处理</span></span><br><span class="line">  <span class="keyword">if</span> (to.name !== <span class="string">'Home'</span>) &#123;</span><br><span class="line">    <span class="comment">// 倒序遍历数组获取匹配到的路由节点，拼接各部分title</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = to.matched.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">      titleStr += <span class="string">`<span class="subst">$&#123;to.matched[i].meta.title&#125;</span> - `</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 添加站点名</span></span><br><span class="line">  titleStr += title</span><br><span class="line">  <span class="comment">// 更新title</span></span><br><span class="line">  <span class="built_in">document</span>.title = titleStr</span><br><span class="line">  <span class="comment">// 继续路由导航</span></span><br><span class="line">  next()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> router</span><br></pre></td></tr></table></figure></p>
<p>ok，打完收工！现在可以切换路由看看<code>title</code>有没有在变化了。<br>可以看我的Demo<a href="http://vue2.leenty.com" target="_blank" rel="noopener">http://vue2.leenty.com</a>，四处切换路由，看看标题如何变化吧！</p>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><p><a href="http://vue2.leenty.com" target="_blank" rel="noopener">演示地址(http://vue2.leenty.com)</a><br><a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">源码地址(https://github.com/leenty/vue2)</a><br><a href="https://github.com/leenty" target="_blank" rel="noopener">github主页</a>,觉得靠谱的话欢迎加星跟随</p>

      
    </div>
    <div class="article-info article-info-index">
      
      <a href="/2016/12/18/vue2-6/" class="archive-article-date">
  	<time datetime="2016-12-18T14:47:23.000Z" itemprop="datePublished"><i class="icon-clock"></i>2016-12-18</time>
</a>
      
	<div class="article-tag tagcloud">
		<i class="icon-price-tags"></i>
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vue-router/">vue-router</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuejs/">vuejs</a></li></ul>
	</div>

      

      <div class="clearfix"></div>
    </div>
  </div>
</article>










  
    <article id="post-vue2-5" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/12/11/vue2-5/">vue2.0一起在懵逼的海洋里越陷越深（五）</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>本文章系列：<a href="http://leenty.com/tags/vuejs/" target="_blank" rel="noopener">vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)</a><br>之前的几篇文章的说了<code>vue-router</code>以及<code>vuex</code>的简单使用，这次就开始组合这两者进行实际应用。<br>场地呢就在我的<a href="http://vue2.leenty.com" target="_blank" rel="noopener">vue2.0Demo</a>,这是<a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">源码地址</a>,觉得靠谱的话欢迎加星跟随,有问题欢迎评论和指正😃<br>OK交代完毕，说下这回要完成的内容。<br>这回要做的是一个带缩放功能的滑动菜单(就是一个侧拉栏)和文章列表，以及文章的展示路由<br>使用<code>vuex</code>做状态管理控制<code>css</code>完成动画过度效果以及使用<code>vue-router</code>的嵌套路由功能。</p>
<p><strong> 滴滴滴！上车请刷卡！</strong><br><img src="http://leenty.com/img/vue/shangche.jpg" alt></p>
<h3 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h3><p>首先，我们先把核心功能完成，也就是<code>vue-router</code>的嵌套路由功能 </p>
<h4 id="嵌套路由功能"><a href="#嵌套路由功能" class="headerlink" title="嵌套路由功能"></a>嵌套路由功能</h4><p>有些时候我们会遇到一个模板重复使用的情况，注意我说的并不是一个子模板在其父模板上的重复，而是多个页面之间的使用到相同的父模板。<br>就好比有这么几个路径</p>
<ul>
<li><code>vue2.leenty.com/article/demo1</code></li>
<li><code>vue2.leenty.com/article/demo2</code></li>
<li><code>vue2.leenty.com/article/demo3</code><br>可以发现其中共有的部分<code>vue2.leenty.com/article</code>。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">/article/demo1                 /article/demo2               /article/demo3</span><br><span class="line">+------------------+           +-----------------+          +-----------------+</span><br><span class="line">| article          |           | article         |          | article         |</span><br><span class="line">| +--------------+ |           | +-------------+ |          | +-------------+ |</span><br><span class="line">| | demo1        | |  +-----&gt;  | | demo2       | | +-----&gt;  | | demo3       | |</span><br><span class="line">| |              | |           | |             | |          | |             | |</span><br><span class="line">| +--------------+ |           | +-------------+ |          | +-------------+ |</span><br><span class="line">+------------------+           +-----------------+          +-----------------+</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>没错，这个路径指向的就是父模板，他在多个子路由里被重复的渲染，如果我们没有对其做嵌套路由的处理，结果将是不仅我们写的累，vuejs渲染的也多余，因为这个模板被反复的使用却每次都被重新渲染。<br>so，我们开始做嵌套路由吧！<br>打开路由列表文件(<code>routes.js</code>)<br>tips:不要把<code>routes.js</code>和项目里的<code>router.js</code>搞混咯，一个是路由列表文件<code>routes.js</code>，一个是路由导出文件<code>router.js</code><br>在里面我们假定有一个基础的路由（这个文件在本系列第二章里有讲到）<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> routes = [</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Article'</span>,</span><br><span class="line">    path: <span class="string">'/article'</span>,</span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Article.vue'</span>)</span><br><span class="line">    <span class="comment">// 这里因为书写以及以后做异步组件的方便，将原先的import导入的方式改成了require的方式</span></span><br><span class="line">    <span class="comment">// 这么做不会实质上没和之前没有变化的，只是单纯的写法不同。</span></span><br><span class="line">  &#125;</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> routes</span><br></pre></td></tr></table></figure></p>
<p>好，接下来我们加入子路由，<br>目前本系列已经有五篇文章，那么现在一一加入进去。<br>当前的项目路径<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">src</span><br><span class="line">├── main.js               # vuejs应用入口</span><br><span class="line">├── router.js             # 路由导出文件</span><br><span class="line">├── routes.js             # 路由列表文件</span><br><span class="line">├── App.vue               # vuejs应用根模板</span><br><span class="line">├── components</span><br><span class="line">│   ├── Home.vue</span><br><span class="line">│   ├── Article.vue</span><br><span class="line">│   ├── Demo.vue</span><br><span class="line">│   ├── ...               # 存放各个路由入口文件</span><br><span class="line">│   └── templates         # 存放模板</span><br><span class="line">│       ├── AppArticleList.vue    # 文章列表 </span><br><span class="line">│       └── ...</span><br><span class="line">└── store</span><br><span class="line">│   ├── index.js          # 组装模块并导出 store 的地方</span><br><span class="line">│   ├── actions.js        # 根级别的 action</span><br><span class="line">│   ├── mutations.js      # 根级别的 mutation</span><br><span class="line">│   ├── types.js          # mutation命名空间</span><br><span class="line">│   └── modules</span><br><span class="line">│       ├── demo.js       # demo模块</span><br><span class="line">│       └── status.js     # 全局应用状态模块</span><br><span class="line">└── md                    # 存放md文件</span><br><span class="line">    └── articles          # 文章路径 </span><br><span class="line">        ├── vue2-1.vue</span><br><span class="line">        ├── vue2-2.vue</span><br><span class="line">        ├── vue2-3.vue</span><br><span class="line">        ├── vue2-4.vue</span><br><span class="line">        └── vue2-5.vue</span><br><span class="line">        (这里为了讲解方便，会将.md文件替换为.vue文件，)</span><br><span class="line">        (效果是一样的只是怕读者有些乱，.vue文件你们尝试的时候可以写些东西)</span><br></pre></td></tr></table></figure></p>
<p>嵌套路由时会在原有路由对象的基础上添加一个<code>children</code>的节点<br>代码如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> routes = [</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Article'</span>,</span><br><span class="line">    path: <span class="string">'/article'</span>,</span><br><span class="line">    <span class="comment">// 父路由上尽量写绝对路径，不然可能会引起一些麻烦，</span></span><br><span class="line">    <span class="comment">// 有捣(xia)鼓(gao)精神的同学可以试试</span></span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Article.vue'</span>),</span><br><span class="line">    children: [</span><br><span class="line">    <span class="comment">// children节点：传入一个子路由数组，格式与父路由是一样的</span></span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'vue2_1'</span>,</span><br><span class="line">        path: <span class="string">'vue2_1'</span>,</span><br><span class="line">        <span class="comment">// path: 导入的路径是相对路径，你不需要写全，如下的path将会被vuejs理解为：</span></span><br><span class="line">        <span class="comment">// '/article/vue2_1'</span></span><br><span class="line">        <span class="comment">// *** 注意： ***</span></span><br><span class="line">          <span class="comment">// 如果你写的是这样的相对路径，就千万别在前面加'/'，不然就意味着这是一个绝对路径</span></span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./md/articles/vue2-1.vue'</span>)</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'vue2_2'</span>,</span><br><span class="line">        path: <span class="string">'/article/vue2_2'</span>,</span><br><span class="line">        <span class="comment">// 演示一个绝对路径，这样子的路径会被vuejs理解为其本意'/article/vue2_2'</span></span><br><span class="line">        <span class="comment">// 如果这里只写了'/vue2_2'的话，vuejs就会把路由理解为'/vue2_2'，</span></span><br><span class="line">        <span class="comment">// 不过不用担心他显示上的问题，只是url会有些有趣的区别</span></span><br><span class="line">        <span class="comment">// 你会发现虽然url变短了，但是父模板依然正常的显示着。</span></span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./md/articles/vue2-2.vue'</span>)</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'vue2_3'</span>,</span><br><span class="line">        path: <span class="string">'vue2_3'</span>,</span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./md/articles/vue2-3.vue'</span>)</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'vue2_4'</span>,</span><br><span class="line">        path: <span class="string">'vue2_4'</span>,</span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./md/articles/vue2-4.vue'</span>)</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'vue2_5'</span>,</span><br><span class="line">        path: <span class="string">'vue2_5'</span>,</span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./md/articles/vue2-5.vue'</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> routes</span><br></pre></td></tr></table></figure></p>
<p>嗯，好了，这样嵌套路由就建立好了</p>
<h4 id="对侧拉栏做状态管理"><a href="#对侧拉栏做状态管理" class="headerlink" title="对侧拉栏做状态管理"></a>对侧拉栏做状态管理</h4><p>打开<code>src/store/modules/status.js</code><br>代码如下<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> types <span class="keyword">from</span> <span class="string">'../types'</span></span><br><span class="line"><span class="comment">// 引入命名空间，放置在types里</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> getScrollData <span class="keyword">from</span> <span class="string">'../../utils/scroll'</span></span><br><span class="line"><span class="comment">// 这是获得滚动数据的js文件，具体怎样写的可以去我github开源项目里看</span></span><br><span class="line"><span class="comment">// 导出的是一个方法，这个方法返回一个对象</span></span><br><span class="line"><span class="comment">// &#123;</span></span><br><span class="line"><span class="comment">//    scrollTop: 0,</span></span><br><span class="line"><span class="comment">//    scrollHeight: 0,</span></span><br><span class="line"><span class="comment">//    windowHeight: 0,</span></span><br><span class="line"><span class="comment">//    scrollBottom: 0</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> state = &#123;</span><br><span class="line">  articleList: <span class="literal">false</span>,</span><br><span class="line">  <span class="comment">// 布尔值，表示侧拉文章列表的开关</span></span><br><span class="line">  scroll: &#123;</span><br><span class="line">  <span class="comment">// 滚动相关的数据</span></span><br><span class="line">    scrollTop: <span class="number">0</span>,</span><br><span class="line">    scrollHeight: <span class="number">0</span>,</span><br><span class="line">    windowHeight: <span class="number">0</span>,</span><br><span class="line">    scrollBottom: <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> getters = &#123;</span><br><span class="line">  <span class="comment">// articleList: (&#123;status&#125;) =&gt; status.articleList</span></span><br><span class="line">  <span class="comment">// tips: 上面这种方法是错误的。这里的getters传入进来的不是state的根对象，</span></span><br><span class="line">  <span class="comment">// 而是当前的state对象，在这里也就相当于是state = state.status</span></span><br><span class="line">  <span class="comment">// 所以可以放心的用state</span></span><br><span class="line">  articleList: <span class="function"><span class="params">state</span> =&gt;</span> state.articleList</span><br><span class="line">  <span class="comment">// 设置Getters，在.vue文件里可以使用mapGetters方法获得</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> mutations = &#123;</span><br><span class="line">  [types.ARTICLE_LIST] (state) &#123;</span><br><span class="line">    state.articleList = !state.articleList</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 设置mutations，只有这个方法可以改变state</span></span><br><span class="line">  [types.SCROLLDATA] (state, scrollObj) &#123;</span><br><span class="line">    state.scroll = scrollObj</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> actions = &#123;</span><br><span class="line">  articleListSwitch (&#123; commit &#125;) &#123;</span><br><span class="line">    commit(types.ARTICLE_LIST)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 设置actions,可以在这里做一些异步的工作，然后使用commit来调用mutations修改state</span></span><br><span class="line">  pushScrollData (&#123; commit &#125;) &#123;</span><br><span class="line">    commit(types.SCROLLDATA, getScrollData(), &#123; <span class="attr">silent</span>: <span class="literal">true</span> &#125;)</span><br><span class="line">    <span class="comment">// 因为页面滚动触发频繁，会影响到我们平时的vuex的审查，所以这里选择静默提交</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  state,</span><br><span class="line">  getters,</span><br><span class="line">  actions,</span><br><span class="line">  mutations</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 而后的.vue文件就可以调用辅助方法达到获取状态或者控制状态的目的了</span></span><br></pre></td></tr></table></figure></p>
<p>调试vuex最好使用vuejs的谷歌插件<a href="https://chrome.google.com/webstore/detail/nhdogjmejiglipccpnnnanhbledajbpd" target="_blank" rel="noopener">Devtools</a><br>或者去github<a href="https://github.com/vuejs/vue-devtools" target="_blank" rel="noopener">下载源码自己编译</a><br>翻墙要梯子(vpn)，想翻墙没vpn的我这里安利一个vpn，没什么其他，因为我正用的就是这个。<br>贴一个云梯推荐码<a href="http://referyt.com/?r=f688f08a26bf108d" target="_blank" rel="noopener">http://referyt.com/?r=f688f08a26bf108d</a>,通过推荐码注册可以优惠10元，笔者也可以得到10元优惠，在得到优惠的同时也是对我的鼓舞吧😂</p>
<h4 id="渲染链接列表"><a href="#渲染链接列表" class="headerlink" title="渲染链接列表"></a>渲染链接列表</h4><p>接下来要做的就是做链接跳转。<br>切到<code>AppArticleList.vue</code>文件，也就是文章列表页。<br>大家可以在我的Demo里点击左上角的菜单按钮看到这个列表<br>!(AppArticleList.vue)[/img/vue/AppArticleList.jpg]</p>
<p>里面的内容是这样子的<br>(因为内容有些复杂，为了看的清晰点这是我提取出来的核心部分)<br>(源文件可以看<a href="https://github.com/leenty/vue2/blob/master/src/components/templates/AppArticleList.vue" target="_blank" rel="noopener">https://github.com/leenty/vue2/blob/master/src/components/templates/AppArticleList.vue</a>)<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 大致的内容就是渲染一个文章列表 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">template</span> <span class="attr">lang</span>=<span class="string">"pug"</span>&gt;</span></span><br><span class="line">  .articleList(:class="&#123;'articleList--Active': articleList&#125;").l-page--Full</span><br><span class="line">    ul.articleList__content.u-ul--Reset</span><br><span class="line">      li(</span><br><span class="line">        v-for="(item, index) in list",</span><br><span class="line">        // vuejs的for循环，list指向了data里的list数组(看js部分)</span><br><span class="line">        :style="calcDelay(index)",</span><br><span class="line">        // 绑定返回一个css延时代码(在methods方法下)</span><br><span class="line">        // 主要功能是给菜单提供依次进入的动画效果</span><br><span class="line">        @click="articleListSwitch"</span><br><span class="line">        // 绑定点击事件，控制文章列表的出现和隐藏</span><br><span class="line">      ).articleList__li</span><br><span class="line">        router-link(</span><br><span class="line">        // 通过list里的数据循环生成路由链接</span><br><span class="line">          :to="&#123;name: item.name&#125;",</span><br><span class="line">          // 绑定路由链接，这里用了&#123;name: item.name&#125;是因为相对来说，name比path方便</span><br><span class="line">          // item就是之前for循环里的item</span><br><span class="line">          active-class="articleList__link--Active"</span><br><span class="line">          // 之前的文章的第二篇里对路由时匹配的`linkActiveClass`做了配置，</span><br><span class="line">          // 这里用不到原来配置的class,所以可以用这个方法单独的做处理</span><br><span class="line">          // 把匹配到的链接的class改成了'articleList__link--Active'</span><br><span class="line">        ).articleList__link.u-borderBox.u-link__inherit.l-flexV--c</span><br><span class="line">          .articleList__title</span><br><span class="line">            svg.svg__home.u-va--tb</span><br><span class="line">              use(xlink:href="#svg__articleIcon")</span><br><span class="line">            // 这里用的图标是svg的,关于这种用法，如果有兴趣我可以专门的介绍一下</span><br><span class="line">            | &#123;&#123;item.title&#125;&#125; </span><br><span class="line">            // 绑定链接的文字</span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">import</span> &#123; mapActions, mapGetters &#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span></span><br><span class="line"><span class="javascript"><span class="comment">// 导入vuex的两个将要用到的辅助方法</span></span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"><span class="javascript">  <span class="comment">// export defalut是es6的模块导出方法，这里导出一个默认模块，即是一个vue对象</span></span></span><br><span class="line">  data () &#123;</span><br><span class="line"><span class="javascript">    <span class="comment">// 这是一种es6对象字面量的缩写，指向一个函数</span></span></span><br><span class="line"><span class="javascript">    <span class="comment">// 扩展出来就是data: function data () &#123;&#125;</span></span></span><br><span class="line"><span class="javascript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="javascript">      <span class="comment">// 而后在函数里去返回将要用到的数据</span></span></span><br><span class="line"><span class="javascript">      <span class="comment">// 这么做返回的数据可以使用this访问到</span></span></span><br><span class="line">      list: [</span><br><span class="line">        &#123;</span><br><span class="line"><span class="javascript">          name: <span class="string">'vue2_1'</span>,</span></span><br><span class="line"><span class="javascript">          title: <span class="string">'vue2.0一起在懵逼的海洋里越陷越深（一）'</span></span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line"><span class="javascript">          name: <span class="string">'vue2_2'</span>,</span></span><br><span class="line"><span class="javascript">          title: <span class="string">'vue2.0一起在懵逼的海洋里越陷越深（二）'</span></span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line"><span class="javascript">          name: <span class="string">'vue2_3'</span>,</span></span><br><span class="line"><span class="javascript">          title: <span class="string">'vue2.0一起在懵逼的海洋里越陷越深（三）'</span></span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line"><span class="javascript">          name: <span class="string">'vue2_4'</span>,</span></span><br><span class="line"><span class="javascript">          title: <span class="string">'vue2.0一起在懵逼的海洋里越陷越深（四）'</span></span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line"><span class="javascript">          name: <span class="string">'vue2_5'</span>,</span></span><br><span class="line"><span class="javascript">          title: <span class="string">'vue2.0一起在懵逼的海洋里越陷越深（五）'</span></span></span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"><span class="javascript">  computed: mapGetters([<span class="string">'articleList'</span>]),</span></span><br><span class="line"><span class="javascript">  <span class="comment">// vue的计算方法对象,用法和data里的数据是一样的，</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">// 这里使用了mapGetters辅助函数，用来获得vuex的Getters里的articleList</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">// 这个方法会返回一个对象，所以如果没有其他计算方法的话直接赋值给computed就好了</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">// 有的话可以向下面这样: </span></span></span><br><span class="line"><span class="javascript">  <span class="comment">// computed: &#123;</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">//    demo () &#123;</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">//      return this.list[0].name</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">//      在这里你可以使用this访问到data里的list</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">//    &#125;,</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">//    ...mapGetters(['articleList'])</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">//    ...延展操作符，用于展开mapGetters得到的对象，使得与demo属性平级</span></span></span><br><span class="line"><span class="javascript">  <span class="comment">// &#125;,</span></span></span><br><span class="line">  methods: &#123;</span><br><span class="line"><span class="javascript">    <span class="comment">// vue的方法对象，你可以在这里写你的事件处理函数或是其他方法</span></span></span><br><span class="line"><span class="javascript">    calcDelay: <span class="function"><span class="keyword">function</span> (<span class="params">index</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">      <span class="comment">// 这是分配css动画延迟量的函数</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="string">'transitionDelay'</span>: <span class="string">`.<span class="subst">$&#123;index + <span class="number">2</span>&#125;</span>s`</span></span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line"><span class="javascript">    ...mapActions([<span class="string">'articleListSwitch'</span>])</span></span><br><span class="line"><span class="javascript">    <span class="comment">// 通过延展操作符,展开mapActions得到的actions对象</span></span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">lang</span>=<span class="string">"stylus"</span>&gt;</span></span><br><span class="line">  // css就不多说了</span><br><span class="line"><span class="css">  @<span class="keyword">import</span> <span class="string">'../../assets/stylus/preinstall'</span></span></span><br><span class="line"><span class="css">  <span class="selector-class">.articleList</span></span></span><br><span class="line">    background-color c-master</span><br><span class="line"><span class="css">  <span class="selector-class">.articleList__content</span></span></span><br><span class="line">    width s-articleList</span><br><span class="line">    margin-top 8vh</span><br><span class="line">    max-height 84vh</span><br><span class="line"><span class="css">    <span class="selector-tag">color</span> <span class="selector-id">#fff</span></span></span><br><span class="line"><span class="css">  <span class="selector-class">.articleList__li</span></span></span><br><span class="line">    transform translateX(-(s-articleList))</span><br><span class="line"><span class="css">    <span class="selector-tag">transition</span> <span class="selector-tag">transform</span> <span class="selector-class">.3s</span> <span class="selector-tag">cb-duang</span> <span class="selector-class">.2s</span></span></span><br><span class="line"><span class="css">  <span class="selector-class">.articleList__link</span></span></span><br><span class="line">    width 100%</span><br><span class="line"><span class="css">    <span class="selector-tag">line-height</span> 1<span class="selector-class">.3em</span></span></span><br><span class="line">    padding-left 10px</span><br><span class="line">    min-height 50px</span><br><span class="line"><span class="css">    <span class="selector-tag">background-color</span> <span class="selector-tag">rgba</span>(255,255,255,<span class="selector-class">.1</span>)</span></span><br><span class="line"><span class="css">    &amp;<span class="selector-pseudo">:hover</span></span></span><br><span class="line"><span class="css">      <span class="selector-tag">background-color</span> <span class="selector-tag">rgba</span>(255,255,255,<span class="selector-class">.3</span>)</span></span><br><span class="line">    svg</span><br><span class="line">      transform-origin bottom center</span><br><span class="line"><span class="css">      <span class="selector-tag">transform</span> <span class="selector-tag">scale</span>(<span class="selector-class">.7</span>)</span></span><br><span class="line"><span class="css">  <span class="selector-class">.articleList__link--Active</span></span></span><br><span class="line"><span class="css">    <span class="selector-tag">background-color</span> <span class="selector-tag">rgba</span>(255,255,255,<span class="selector-class">.4</span>)</span></span><br><span class="line"><span class="css">  <span class="selector-class">.articleList--Active</span> <span class="selector-class">.articleList__li</span></span></span><br><span class="line">    transform translateX(0)</span><br><span class="line"><span class="css">  <span class="selector-class">.articleList__title</span></span></span><br><span class="line">    display block</span><br><span class="line">    width 100%</span><br><span class="line">    font-size 12px</span><br><span class="line"><span class="css">    &amp;<span class="selector-pseudo">:first-line</span></span></span><br><span class="line">      font-size 14px</span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>在写的过程中碰到了一个浏览器bug，这里还是说下<br>bug: 如果父元素进行了transform变换，那么子元素的position fixed将会失去作用,退化成position absolute<br>解决方案: 之前试过想要使用css的方式去绕过这个问题，但是发现不行，无奈使用了js去计算子元素退化成absolute后的差值，对其进行位移达到视觉的效果。<br>有兴趣的可以打开<a href="http://vue2.leenty.com/article/vue2_2" target="_blank" rel="noopener">http://vue2.leenty.com/article/vue2_2</a>然后审查元素，查看我的导航条也就是<code>.header__content</code>，这个时候你打开侧边栏然后上下滚动就会看到<code>.header__content</code>上js所不全的差值了</p>
<h4 id="装载嵌套路由"><a href="#装载嵌套路由" class="headerlink" title="装载嵌套路由"></a>装载嵌套路由</h4><p>打开<code>article.vue</code>文件，文件很简单，内容如下：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span> <span class="attr">lang</span>=<span class="string">"pug"</span>&gt;</span></span><br><span class="line">.article</span><br><span class="line">  h1.l-ta--c 文章页面</span><br><span class="line">  .md-content</span><br><span class="line">    router-view</span><br><span class="line">    // 这个就是二级路由的装载点了</span><br><span class="line">    // 之前的`APP.vue`的`router-view`会装载当前模板，而后的文章都会装载到这个点上。</span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">    data () &#123;</span><br><span class="line"><span class="javascript">      <span class="keyword">return</span> &#123;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">lang</span>=<span class="string">"stylus"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<h4 id="关于触发滚动之后的一系列事件"><a href="#关于触发滚动之后的一系列事件" class="headerlink" title="关于触发滚动之后的一系列事件"></a>关于触发滚动之后的一系列事件</h4><p>关于触发滚动，考虑到之后可能会有多个页面需要使滚动方面的数据，所以就放在了vuex里作为状态的一部分。<br>所以滚动的监听就只需要监听一次就好了，多个地方的监听会浪费资源<br>最终，我把监听放在了<code>App.vue</code>里面,在里面监听’scroll’事件，然后放在vuex上，供有需要的组件去使用</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span> <span class="attr">lang</span>=<span class="string">"pug"</span>&gt;</span></span><br><span class="line">  .app.u-clearfix</span><br><span class="line">    app-article-list</span><br><span class="line">    .app__content(</span><br><span class="line">      :class="&#123;'app__content--Active': articleList&#125;",</span><br><span class="line">      // 如果侧拉文章列表打开，那么添加这个class，相应的css效果将被触发</span><br><span class="line">      @scroll="pushScrollData"</span><br><span class="line">      // 绑定scroll事件</span><br><span class="line">    ).l-page--Full</span><br><span class="line">      home-header</span><br><span class="line">      .app__bodyer.l-mH--auto</span><br><span class="line">        router-view</span><br><span class="line">    include ./assets/svg/all</span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">import</span> HomeHeader <span class="keyword">from</span> <span class="string">'./components/templates/HomeHeader.vue'</span></span></span><br><span class="line"><span class="javascript">  <span class="keyword">import</span> AppArticleList <span class="keyword">from</span> <span class="string">'./components/templates/AppArticleList.vue'</span></span></span><br><span class="line"><span class="javascript">  <span class="keyword">import</span> &#123; mapGetters, mapActions &#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span></span><br><span class="line"><span class="javascript">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">    components: &#123;</span><br><span class="line">      HomeHeader,</span><br><span class="line">      AppArticleList</span><br><span class="line">    &#125;,</span><br><span class="line">    computed: mapGetters([</span><br><span class="line"><span class="javascript">      <span class="string">'articleList'</span></span></span><br><span class="line">    ]),</span><br><span class="line">    methods: &#123;</span><br><span class="line">      ...mapActions([</span><br><span class="line"><span class="javascript">        <span class="string">'pushScrollData'</span>,</span></span><br><span class="line"><span class="javascript">        <span class="string">'articleListSwitch'</span></span></span><br><span class="line">      ])</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">lang</span>=<span class="string">"stylus"</span>&gt;</span></span><br><span class="line"><span class="css">  @<span class="keyword">import</span> <span class="string">'./assets/stylus/main'</span></span></span><br><span class="line"><span class="css">  <span class="selector-class">.app__menu</span></span></span><br><span class="line">    background-color c-master</span><br><span class="line"><span class="css">  <span class="selector-class">.app__content</span></span></span><br><span class="line">    overflow auto</span><br><span class="line"><span class="css">    <span class="selector-tag">transition</span> <span class="selector-tag">transform</span> <span class="selector-class">.5s</span></span></span><br><span class="line"><span class="css">    <span class="selector-tag">box-shadow</span> 0 0 100<span class="selector-tag">px</span> 5<span class="selector-tag">px</span> <span class="selector-tag">rgba</span>(0,0,0,0<span class="selector-class">.3</span>)</span></span><br><span class="line">    background-color c-bgc</span><br><span class="line">    transform-origin s-articleList center</span><br><span class="line"><span class="css">  <span class="selector-class">.app__content--Active</span></span></span><br><span class="line"><span class="css">    <span class="selector-tag">transform</span> <span class="selector-tag">scale</span>(<span class="selector-class">.9</span>) <span class="selector-tag">translateX</span>(<span class="selector-tag">s-articleList</span>)</span></span><br><span class="line"><span class="css">  <span class="selector-class">.app__bodyer</span></span></span><br><span class="line">    max-width max-width</span><br><span class="line">    background-color c-bgc</span><br><span class="line"><span class="css">  @<span class="keyword">media</span> screen and (max-width: max-width)</span></span><br><span class="line"><span class="css">    <span class="selector-class">.app__bodyer</span></span></span><br><span class="line">      padding 0 10px</span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>ok，这么个流程走下来，算是把<code>vuejs</code>,<code>vue-router</code>和<code>vuex</code>用在了一起</p>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><p><a href="http://vue2.leenty.com" target="_blank" rel="noopener">演示地址(http://vue2.leenty.com)</a><br><a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">源码地址(https://github.com/leenty/vue2)</a><br><a href="https://github.com/leenty" target="_blank" rel="noopener">github主页</a>,觉得靠谱的话欢迎加星跟随</p>

      
    </div>
    <div class="article-info article-info-index">
      
      <a href="/2016/12/11/vue2-5/" class="archive-article-date">
  	<time datetime="2016-12-11T14:20:04.000Z" itemprop="datePublished"><i class="icon-clock"></i>2016-12-11</time>
</a>
      
	<div class="article-tag tagcloud">
		<i class="icon-price-tags"></i>
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/css/">css</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vue-router/">vue-router</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuejs/">vuejs</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuex/">vuex</a></li></ul>
	</div>

      

      <div class="clearfix"></div>
    </div>
  </div>
</article>










  
    <article id="post-vue2-4" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/12/04/vue2-4/">vue2.0一起在懵逼的海洋里越陷越深（四）</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>本文章系列：<a href="http://leenty.com/tags/vuejs/" target="_blank" rel="noopener">vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)</a><br>前面一篇讲了vue-router的<code>router-link</code>,<br>有读者说希望能先看到vuex的文章<br>其实vuex在我的vue2.0的demo里已经在使用了<br>想想确实应该先来点vuex的了，因为有些有关的状态管理急需vuex的加入<br>好，那么这次就先上vuex吧！</p>
<h3 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h3><p>OK！先介绍下vuex<br>vuex是vuejs的状态管理方案<br>因为vuex有些复杂，一般应用在较复杂的状态环境下，如果是比较简单的应用就不需要安装vuex了</p>
<h4 id="vuex单向数据流"><a href="#vuex单向数据流" class="headerlink" title="vuex单向数据流"></a>vuex单向数据流</h4><p><img src="http://leenty.com/img/vue/flow.png" alt="vuex单向数据流"><br>如上图所示是vuex单向数据流的流程</p>
<p><strong> 我知道，如果是第一次接触这玩意，到这就懵逼了，就像我第一次看文档一样 </strong><br><img src="http://leenty.com/img/face/mengbi3.jpg" alt="vuex单向数据流"></p>
<p><strong> 下面解释下<code>State</code> </strong><br>前面说了vuex是vuejs的状态管理方案，这里的状态就是图中的<code>state</code><br>在平时写写前端的过程中，都会涉及到状态的问题，<br>比如你看到了一篇文章写的不错，就想要收藏，<br>然后又对作者有些兴趣，于是又加了关注，当然这些最后都是需要前端来表达出来<br>这里面就涉及了两个状态就是收藏与关注<br>这里的收藏与关注我们可以将其用一个变量来表示，当然如这两种只存在两个相对状态的用布尔值(<code>bool</code>)来表示就可以了</p>
<p><strong> 然后是<code>view</code> </strong><br><code>view</code>就是视图,也就是前端所写的页面，前面的<code>state</code>就可以在<code>view</code>里面得到体现，即是你看到的是否关注了作者</p>
<p><strong> 而后是<code>Actions</code> </strong><br><code>Actions</code>是<code>View</code>用来改变<code>State</code>的方法，通过改变<code>State</code>从而改变<code>View</code>的显示</p>
<p>这么说有些抽象，打个比方<br>假设学生小明生病了<br>小明要向班主任请假(小明就是<code>View</code>，小明想改变自己的显示状态，从上学状态变成请假状态)<br>于是小明口头向班主任请假(请假就是<code>Actions</code>，小明通过请假这一个方法达到请假的目的)<br>班主任批准，小明请假成功(班主任就是<code>State</code>的提供者，小明通过请假方法使班主任改变小明的<code>State</code>状态)<br>着也就解释了为什么要有这个流程，有了这个流程就可以统一管理各个<code>view</code>的各个状态</p>
<h4 id="vuex多个组件共享状态"><a href="#vuex多个组件共享状态" class="headerlink" title="vuex多个组件共享状态"></a>vuex多个组件共享状态</h4><p>先贴个流程图，懵逼是没啥关系的<br><img src="http://leenty.com/img/vue/vuex.png" alt="vuex多个组件共享状态"><br>可以看到这一张图比前面一张复杂了许多，其实里面的实线框就是上图的升级版</p>
<p>情况是这样，原来小明学校里这段时间许多同学得了流感，于是同学们一窝蜂的要求请假，<br>学校里因为人太多，又没有一个记录，人数清点不过来了，于是班主任要求请假必须提交请假条</p>
<p>好的，来解释下上图内的实线部分，之前的<code>View</code>在这里改名成了<code>Vue Components</code>,代表了多个组件(这里即是指多个同学)<br>包括小明在内的多个同学<code>Vue Components</code>都得了流感，一起想要请假<code>Actions</code>(他们即将共享一个请假状态)，小明代表多个同学写了一张请假条交给班主任(<code>State</code>提供者)签字同意(签字同意这个动作就是<code>Mutations</code>，触发了<code>State</code>的改变),班主任同意后统一给他们改变了<code>State</code>（请假成功）</p>
<p>这里的多了一个同步与异步的区别，其中<code>Mutations</code>只受理同步处理，而<code>Actions</code>就是执行异步操作的函数，作为代价，<code>Actions</code>不再能直接触发改变<code>State</code>状态，而是需通过<code>Mutations</code>来触发<code>State</code>的改变</p>
<p>情况是这样，因为不只是一个班的学生得了流感，请假的人比较多，学校<code>Backend API</code>需要做一个统计，于是请假需要得到学校专门的请假条的并通过学校签字才能生效，这里就有了虚线部分。<br>请假<code>Actions</code>改变<code>State</code>的方法不再是仅仅班主任签字就可以了，而是需要通过学校这个前提，于是<code>Actions</code>就变成了一个异步请求，需要得到学校<code>Backend API</code>的专门的请假条和签字同意后，才能向班主任提交改变<code>State</code>的申请</p>
<p>这里想要表达的意思就是，<code>Vue Components</code>改变自身状态需要通过<code>Actions</code>（有需要的话要向后端接口<code>Backend API</code>发送请求）来操作<code>Mutations</code>改变<code>State</code>从而改变自身状态。<br>至于图中没有说到的<code>Devtools</code>是一个开发者工具，是一个便于查看和管理vue应用以及vuex状态的浏览器插件。<br>你可以在里面看到你vue对象和vuex每一次的commit，commit后面会说到。还有你当前的应用状态<br><img src="http://leenty.com/img/vue/devtools.png" alt="devtools"><br>附上一个<a href="https://github.com/vuejs/vue-devtools" target="_blank" rel="noopener">devtools库地址</a></p>
<h4 id="架构vuex"><a href="#架构vuex" class="headerlink" title="架构vuex"></a>架构vuex</h4><p>项目结构：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">├── main.js</span><br><span class="line">├── App.vue</span><br><span class="line">├── components</span><br><span class="line">│   ├── Home.vue</span><br><span class="line">│   └── ...</span><br><span class="line">└── store</span><br><span class="line">    ├── index.js          # 组装模块并导出 store 的地方</span><br><span class="line">    ├── actions.js        # 根级别的 action</span><br><span class="line">    ├── mutations.js      # 根级别的 mutation</span><br><span class="line">    ├── types.js          # mutation命名空间</span><br><span class="line">    └── modules</span><br><span class="line">        ├── demo.js       # demo模块</span><br><span class="line">        └── status.js     # 全局应用状态模块</span><br></pre></td></tr></table></figure></p>
<p>结构可以根据个人需要进行调整</p>
<p><strong> 下面开始构建<code>store/index.js</code> </strong><br>当然在这之前，如果没有安装vuex的需要先安装<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i vuex -S</span><br></pre></td></tr></table></figure></p>
<p>由于vuex的内容太多，这里先说基础用法<br>首先为<code>store/index.js</code>编写内容<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="comment">// 导入vue</span></span><br><span class="line"><span class="keyword">import</span> Vuex <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line"><span class="comment">// 导入vuex</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> status <span class="keyword">from</span> <span class="string">'./modules/status'</span></span><br><span class="line"><span class="comment">// 导入status模块（这是我管理全局应用状态的模块）</span></span><br><span class="line"><span class="keyword">import</span> demo <span class="keyword">from</span> <span class="string">'./modules/demo'</span></span><br><span class="line"><span class="comment">// 导入demo模块（这个的部分演示可以在http://vue2.leenty.com/demo/vuex_state/里看到）</span></span><br><span class="line"></span><br><span class="line">Vue.use(Vuex)</span><br><span class="line"><span class="comment">// 告诉vue将要使用vuex</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> debug = process.env.NODE_ENV !== <span class="string">'production'</span></span><br><span class="line"><span class="comment">// env里去获取当前的环境是否需要开启严格模式</span></span><br><span class="line"><span class="comment">// 在发布环境开启严格模式会造成性能上不必要的损失</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line"><span class="comment">// 默认导出vuex模块</span></span><br><span class="line">  modules: &#123;</span><br><span class="line">  <span class="comment">// 导入模块</span></span><br><span class="line">    status,</span><br><span class="line">    demo</span><br><span class="line">  &#125;,</span><br><span class="line">  strict: debug</span><br><span class="line">  <span class="comment">// 是否开启严格模式</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p><strong> 构建state模块 </strong><br>这里以<code>demo.js</code>为例</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> types <span class="keyword">from</span> <span class="string">'../types'</span></span><br><span class="line"><span class="comment">// 导入mutations的命名空间</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> state = &#123;</span><br><span class="line"><span class="comment">// 定义state</span></span><br><span class="line">  demoFollow: <span class="literal">false</span>,</span><br><span class="line">  <span class="comment">// 这里模拟的是关注的状态，布尔值表示是否关注</span></span><br><span class="line">  demoFollowPending: <span class="literal">false</span></span><br><span class="line">  <span class="comment">// 是否在请求中(actions是否在执行异步操作)</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> getters = &#123;</span><br><span class="line"><span class="comment">// 定义getters, getters是对state的扩展，可以以state衍生出其他状态</span></span><br><span class="line">  demoFollowStatus: <span class="function"><span class="params">state</span> =&gt;</span> state.demoFollow ? <span class="string">'已关注'</span> : <span class="string">'未关注'</span></span><br><span class="line">  <span class="comment">// demoFollowStatus是demoFollow的衍生量，将原来的布尔值映射为'已关注' : '未关注'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> mutations = &#123;</span><br><span class="line"><span class="comment">// 只有mutations才能操作改变state，mutations是同步执行的</span></span><br><span class="line"><span class="comment">// 所以有关异步的操作请放在actions里执行</span></span><br><span class="line">  [types.DEMO__VUEX_FOLLOW] (state, status = <span class="literal">NaN</span>) &#123;</span><br><span class="line">  <span class="comment">// 使用预定义好的名字来写mutations方法</span></span><br><span class="line">    state.demoFollow = <span class="built_in">isNaN</span>(status) ? !state.demoFollow : status</span><br><span class="line">  &#125;,</span><br><span class="line">  [types.DEMO__VUEX_FOLLOW_PENDING] (state, status = <span class="literal">NaN</span>) &#123;</span><br><span class="line">  <span class="comment">// 这里对status传值做了审查，如没有传，则对要改变的布尔值进行取反操作</span></span><br><span class="line">    state.demoFollowPending = <span class="built_in">isNaN</span>(status) ? !state.demoFollowPending : status</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> actions = &#123;</span><br><span class="line"><span class="comment">// actions是可以执行异步操作的，操作完毕后触发mutations里的方法去改变state的状态</span></span><br><span class="line">  demoFollowAjax (&#123;commit&#125;, status) &#123;</span><br><span class="line">    commit(types.DEMO__VUEX_FOLLOW_PENDING)</span><br><span class="line">    <span class="comment">// 在异步操作前通过mutations告诉应用，现在正在进行异步操作</span></span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 利用延时函数模拟异步的ajax操作</span></span><br><span class="line">      commit(types.DEMO__VUEX_FOLLOW_PENDING)</span><br><span class="line">      <span class="comment">// commit 是在actions里用来触发mutations的方法</span></span><br><span class="line">      <span class="comment">// 告诉应用，异步操作结束</span></span><br><span class="line">      commit(types.DEMO__VUEX_FOLLOW, status)</span><br><span class="line">      <span class="comment">// 为关注按钮赋予新的状态</span></span><br><span class="line">    &#125;, <span class="number">2000</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line"><span class="comment">// 导出整个demo模块</span></span><br><span class="line">  state,</span><br><span class="line">  getters,</span><br><span class="line">  actions,</span><br><span class="line">  mutations</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong> 这里解释下mutations里的方法的奇怪写法，我知道如果对es6于法了解不多这里是会懵逼的 </strong><br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mutations = &#123;</span><br><span class="line">  [types.DEMO__VUEX_FOLLOW] (state, status = <span class="literal">NaN</span>) &#123;</span><br><span class="line">    state.demoFollow = <span class="built_in">isNaN</span>(status) ? !state.demoFollow : status</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这是对象内方法的简化写法，其中<code>types.DEMO__VUEX_FOLLOW</code>是在<code>types.js</code>里预定义的，内容如下<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> DEMO__VUEX_FOLLOW = <span class="string">'DEMO__VUEX_FOLLOW'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> DEMO__VUEX_FOLLOW_PENDING = <span class="string">'DEMO__VUEX_FOLLOW_PENDING'</span></span><br><span class="line"><span class="comment">// 其实就是字符串集合，最后用 import * as types from '../types' 方法导入vuex模块里</span></span><br><span class="line"><span class="comment">// 就变成了一个types对象</span></span><br></pre></td></tr></table></figure></p>
<p>上例中全部展开是这样的<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mutations = &#123;</span><br><span class="line">  [types.DEMO__VUEX_FOLLOW]: <span class="function">(<span class="params">state, status = <span class="literal">NaN</span></span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// [types.DEMO__VUEX_FOLLOW]是提取types.DEMO__VUEX_FOLLOW的值的一种方式</span></span><br><span class="line">  <span class="comment">// 在这里[types.DEMO__VUEX_FOLLOW]提取出来就是types.js里预定义的'DEMO__VUEX_FOLLOW'</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">isNaN</span>(status)&#123;</span><br><span class="line">      state.demoFollow = !state.demoFollow</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      state.demoFollow = status</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>好，到此为止，vuex就已经建立好了，下面就说如何使用了</p>
<h4 id="应用状态的使用与改变"><a href="#应用状态的使用与改变" class="headerlink" title="应用状态的使用与改变"></a>应用状态的使用与改变</h4><p>vuex提供了4个辅助函数<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapState, mapGetters, mapActions, mapMutations &#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span><br></pre></td></tr></table></figure></p>
<p>是分别用来获取<code>State, Getters, Actions, Mutations</code>的map方法<br>在vue Components里面你可以以这样的方式来导入需要使用的方法</p>
<p>这4个方法拥有统一的参数格式以及一个统一的返回格式<br>可以传入一个数组<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mapGetters([<span class="string">'demoFollowStatus'</span>])</span><br><span class="line"><span class="comment">// 此方法导出的是一个Getters对象</span></span><br><span class="line">mapGetters(&#123;</span><br><span class="line">  demoFollow: <span class="string">'demoFollowStatus'</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 可以通过传入对象的形式来改变得到的getters方法名</span></span><br></pre></td></tr></table></figure></p>
<p>同理，不同的map方法会导出各自的方法<br>其中<code>mapState, mapGetters</code>将会导出适用于<code>computed</code>的方法<br>而<code>mapMutations, mapActions</code>将会导出适用于<code>methods</code>的方法</p>
<p>这里以一个demo组件为例<a href="https://github.com/leenty/vue2/blob/master/src/components/DemoVuexState.vue" target="_blank" rel="noopener">DemoVuexState.vue</a><br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapState, mapGetters, mapMutations, mapActions &#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  data () &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  computed: &#123;</span><br><span class="line">  <span class="comment">// vue的计算属性，计算属性内方法的私有变量变动会触发这个属性的重新计算</span></span><br><span class="line">    ...mapState(&#123;</span><br><span class="line">      mapStateFollow: <span class="function">(<span class="params">&#123;demo&#125;</span>) =&gt;</span> demo.demoFollow,</span><br><span class="line">      mapStateFollowPending: <span class="function">(<span class="params">&#123;demo&#125;</span>) =&gt;</span> demo.demoFollowPending</span><br><span class="line">    &#125;),</span><br><span class="line">    <span class="comment">// mapState()直接读取State里的状态内容</span></span><br><span class="line">    ...mapGetters([<span class="string">'demoFollowStatus'</span>])</span><br><span class="line">    <span class="comment">// mapGetters()通过getters转化state从而得到你想要的内容</span></span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">  <span class="comment">// vue的方法，可以是一个事件的方法，也可以是一个vuex的方法，也可以是一个普通函数</span></span><br><span class="line">    ...mapMutations([<span class="string">'DEMO__VUEX_FOLLOW'</span>]),</span><br><span class="line">    <span class="comment">// 同步的改变状态</span></span><br><span class="line">    ...mapActions([<span class="string">'demoFollowAjax'</span>])</span><br><span class="line">    <span class="comment">// 异步的改变状态</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这段代码是一个demo里的片段，效果大家可以看<a href="http://vue2.leenty.com/demo/vuex_state" target="_blank" rel="noopener">这个呆萌</a>，如果开心了可以在<a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">github库里加个星</a>，如果有问题可以在下方评论里讨论讨论😀</p>

      
    </div>
    <div class="article-info article-info-index">
      
      <a href="/2016/12/04/vue2-4/" class="archive-article-date">
  	<time datetime="2016-12-04T12:35:32.000Z" itemprop="datePublished"><i class="icon-clock"></i>2016-12-04</time>
</a>
      
	<div class="article-tag tagcloud">
		<i class="icon-price-tags"></i>
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuejs/">vuejs</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuex/">vuex</a></li></ul>
	</div>

      

      <div class="clearfix"></div>
    </div>
  </div>
</article>










  
    <article id="post-vue2-3" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/11/27/vue2-3/">vue2.0一起在懵逼的海洋里越陷越深（三）</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <!-- [](https://chrome.google.com/webstore/detail/markdown-here/elifhakcjgalahccnjkneoccemfahfoa/related) -->
<p>本文章系列：<a href="http://leenty.com/tags/vuejs/" target="_blank" rel="noopener">vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)</a><br>前面写了vue-router组件的初步用法，原来这次想写vuex的，但是想想还是先继续把vue-router写完吧🤔<br><img src="/img/vue/chiss.jpg" alt="vue2.0"></p>
<h3 id="上回说到-vue-router的基本用法，下面继续深入"><a href="#上回说到-vue-router的基本用法，下面继续深入" class="headerlink" title="上回说到: vue-router的基本用法，下面继续深入"></a>上回说到: vue-router的基本用法，下面继续深入</h3><p>啊不！是继续向着懵逼海洋的海底继续下沉，哈哈哈哈<br>前面已经设置了两个路由，一个是首页，一个是文章页，现在在开一个演示页的路由<br>首页以后顶多就展示下大致的新内容，文章页顶多放放文章详情<br>这演示页可就厉害了，接下来的一些演示都会放在这里，具体的布局还没想好，先这么用着吧！</p>
<h3 id="vue-router的超链接标签“router-link”"><a href="#vue-router的超链接标签“router-link”" class="headerlink" title="vue-router的超链接标签“router-link”"></a>vue-router的超链接标签“router-link”</h3><p>在vue1.0版本的超链接标签还是原来的<code>a</code>标签，链接地址由<code>v-link</code>属性控制(具体的这里也不多说了，vue1.0已经过去啦)<br>而vue2.0版本里超链接标签由<code>a</code>标签被替换成了<code>router-link</code>标签，当然，没有必要不用担心什么，因为最后没有什么特殊的设置的话，<code>router-link</code>标签还是会被渲染成<code>a</code>标签的。<br>至于为什么在vue2.0的时候被替换成了<code>router-link</code>标签呢？<br>大致YY了下，部分情节应该是这样的：</p>
<ul>
<li>最主要情况，在上个版本中，链接只能以<code>a</code>标签的形式存在，不能满足一些特殊的要求，比如在列表(<code>ul&gt;li</code>)下，你需要为在里下面再加上一个<code>a</code>链接才能完成点击列表跳转页面，so2.0版本中路由从<code>a</code>标签变成了可以任意渲染成各种元素的<code>router-link</code>标签，如此一来，就可以直接渲染成<code>li</code>标签，省下了<code>a</code>标签(具体怎么做下面会统一说明)</li>
<li>为什么不直接使用正常<code>a</code>标签写法做链接跳转呢？当点击正常的<code>a</code>链接时，就会感觉到页面跳转时的页面刷新重载的感觉，因为这个<code>a</code>标签并没有被vue-router所监听到事件的触发，所以就会发生正常的页面跳转，所以页面就会重载。那是传统的网页上才会发生的事。使用了vue-router组件所提供的<code>router-link</code>后，页面内的a标签就会被vue所监听，以便在用户点击链接的时候阻止浏览器的默认跳转行为，而转为无刷新加载的方式。当然这只作用于自己的站点内。</li>
</ul>
<h3 id="“router-link”标签的属性-Props"><a href="#“router-link”标签的属性-Props" class="headerlink" title="“router-link”标签的属性(Props)"></a>“router-link”标签的属性(Props)</h3><p>没错，只要是标签，多多少少都是有属性的，最次class和id属性也是可以添加的。<br>下面说说<code>router-link</code>标签的各个属性</p>
<h4 id="“to”属性"><a href="#“to”属性" class="headerlink" title="“to”属性"></a>“to”属性</h4><p><code>to</code>属性最简单的用法就是如<code>a</code>标签里的<code>href</code>属性一样的填写，简单粗暴，想去哪就去哪。<br>其实，<code>to</code>属性的值可以有两种：</p>
<p><strong> 其一为字符串形式，也就是前面说到的如<code>href</code>一样的用法 </strong><br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 字符串 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/article"</span>&gt;</span>Article<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 渲染结果 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/article"</span>&gt;</span>Article<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p><strong> 其二为对象形式，下面看看to属性的 对象的主要结构 </strong><br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 主要结构</span></span><br><span class="line">&#123;</span><br><span class="line">  name: <span class="string">'Article'</span></span><br><span class="line">&#125;</span><br><span class="line">  <span class="comment">// 或者</span></span><br><span class="line">&#123;</span><br><span class="line">  path: <span class="string">'/article'</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 二者选其中之一，如果两种都使用，那么vue会选择使用name字段</span></span><br><span class="line"><span class="comment">// eg</span></span><br><span class="line">&#123;</span><br><span class="line">  name: <span class="string">'Article'</span>,</span><br><span class="line">  path: <span class="string">'/demo'</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 实际效果等同于:</span></span><br><span class="line">&#123;</span><br><span class="line">  name: <span class="string">'Article'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对于里面的<code>path</code>字段，其实就是就是想去哪就去哪的to属性字符串的对象形式<br>至于<code>name</code>字段，是不是会有些懵逼？这个<code>name</code>其实就是上一篇里说到的<code>routes.js</code>文件里的<code>name</code>字段啦！<br>就是这个！填成一样的就好啦！注意大小写哦<br><img src="/img/vue/name-routes.js.png" alt="routes.js-name字段"></p>
<p><strong> to属性的 对象的可选结构 </strong><br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  name: <span class="string">'Article'</span>, <span class="comment">// 与path字段二选一</span></span><br><span class="line">  path: <span class="string">'/article'</span>, <span class="comment">// 与name字段二选一</span></span><br><span class="line">  params: &#123; <span class="comment">// 可选字段 隐性的传递参数(多用来页面传参)</span></span><br><span class="line">    userId: <span class="number">123</span> <span class="comment">// 传递的参数demo</span></span><br><span class="line">  &#125;,</span><br><span class="line">  query: &#123; <span class="comment">// 可选字段 查询参数，就是url里‘?’之后的部分</span></span><br><span class="line">    plan: <span class="string">'private'</span> <span class="comment">// 查询参数demo</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以使用chrome插件<a href="https://chrome.google.com/webstore/detail/nhdogjmejiglipccpnnnanhbledajbpd" target="_blank" rel="noopener">vue.js devtools</a>来查看vue的路由的params参数，安装这个插件需要翻墙下载<br>或者可以去<a href="https://github.com/vuejs/vue-devtools" target="_blank" rel="noopener">github上下代码编译插件</a>,如果觉得麻烦也可以百度去其他网站下<br>对于可选参数是不是会有些懵，下面贴几张图就明白了<br><img src="/img/vue/show-router-param.png" alt="查看路由参数"><br>其中<code>params</code>是隐性传递，<code>query</code>是显性传递。<br><img src="/img/vue/router-query.png" alt="路由query"><br>红框部分就是传递的<code>query</code>了</p>
<h4 id="“replace”属性"><a href="#“replace”属性" class="headerlink" title="“replace”属性"></a>“replace”属性</h4><p>顾名思义，replace是替换的意思，所以在<code>router-link</code>标签添加了这个属性后，页面切换时不会留下历史记录<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">:to</span>=<span class="string">"&#123; path: '/abc'&#125;"</span> <span class="attr">replace</span>&gt;</span><span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<h4 id="“append”属性"><a href="#“append”属性" class="headerlink" title="“append”属性"></a>“append”属性</h4><p>append会把当前路径设置为相对路径，何为相对路径？比如你当前在<code>vue2.leenty.com/demo</code>下，点击这个链接<code>&lt;router-link :to=&quot;{ path: &#39;article&#39;}&quot; append&gt;&lt;/router-link&gt;</code>,如果没带<code>append</code>属性，那么就会跳到<code>vue2.leenty.com/article</code>下(hash模式下是<code>vue2.leenty.com/#/article</code>)，而现在却是跳到了<code>vue2.leenty.com/demo/article</code>下。这个属性用处不是很大，在特殊情况下才会用到。<br>推荐还是把自己地址写全，不要使用相对地址，这样容易搞错<br>另外加个小技巧，在地址前加<code>/</code>能保证是跳转根目录的</p>
<h4 id="“tag”属性"><a href="#“tag”属性" class="headerlink" title="“tag”属性"></a>“tag”属性</h4><p>具有<code>tag</code>属性的的<code>router-link</code>标签会被渲染为相应的标签<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/article"</span> <span class="attr">tag</span>=<span class="string">"li"</span>&gt;</span>article<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>将会被渲染为<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">li</span>&gt;</span>article<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>这里不需要担心li的跳转问题，vue会自动为其绑定点击事件，并跳转页面</p>
<h4 id="“active-class”属性"><a href="#“active-class”属性" class="headerlink" title="“active-class”属性"></a>“active-class”属性</h4><p>这个属性如字面意思上说的，是设置激活链接时的<code>class</code>属性<br>即是当前页面所有与当前地址所匹配的链接都会被添加这个<code>class</code>属性<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/article"</span> <span class="attr">active-class</span>=<span class="string">"u-link--Active"</span>&gt;</span>article<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>如此，在<code>vue2.leenty.com/article</code>页面下(hash模式下是<code>vue2.leenty.com/#/article</code>)就会被渲染为<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/article"</span> <span class="attr">class</span>=<span class="string">"u-link--Active"</span>&gt;</span><span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p><code>active-class</code>属性的默认值是<code>router-link-active</code>,所以如果没有设置，就会被渲染为这个class</p>
<p>其实在上一章节有说到统一的设置这个active-class属性<br>打开<code>router.js</code>文件就能看到<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  mode: <span class="string">'hash'</span>,</span><br><span class="line">  linkActiveClass: <span class="string">'u-link--Active'</span>, <span class="comment">// 这是链接激活时的class</span></span><br><span class="line">  routes</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<h4 id="“exact”属性"><a href="#“exact”属性" class="headerlink" title="“exact”属性"></a>“exact”属性</h4><p>开启<code>router-link</code>的严格模式<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/"</span> <span class="attr">exact</span>&gt;</span>home<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>上面这个标签如果不加<code>exact</code>属性，则会在<code>vue2.leenty.com/article</code>页面下也会被匹配到，<br>这却不是我们的本意,在加了这个属性后就会正确的匹配到<code>vue2.leenty.com</code>下</p>
<p>以上为vue-router的router-link的介绍</p>

      
    </div>
    <div class="article-info article-info-index">
      
      <a href="/2016/11/27/vue2-3/" class="archive-article-date">
  	<time datetime="2016-11-27T14:51:49.000Z" itemprop="datePublished"><i class="icon-clock"></i>2016-11-27</time>
</a>
      
	<div class="article-tag tagcloud">
		<i class="icon-price-tags"></i>
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vue-router/">vue-router</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuejs/">vuejs</a></li></ul>
	</div>

      

      <div class="clearfix"></div>
    </div>
  </div>
</article>










  
    <article id="post-vue2-2" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/11/20/vue2-2/">vue2.0一起在懵逼的海洋里越陷越深（二）</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>本文章系列：<a href="http://leenty.com/tags/vuejs/" target="_blank" rel="noopener">vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)</a></p>
<h3 id="说好了一起懵逼，那么我们继续下沉"><a href="#说好了一起懵逼，那么我们继续下沉" class="headerlink" title="说好了一起懵逼，那么我们继续下沉"></a>说好了一起懵逼，那么我们继续下沉</h3><p>在上一篇里已经将vue2.0需要的依赖都装齐了<br>那么接下来<br><img src="/img/vue/vue2-2.png" alt="vue2.0"><br>因为vue最后生成的页面看似静态页面(对于静态页面这里有些偷鸡用法，不管你怎样，反正我已经露出了诡异的微笑😏，再贴一个<a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">vue2.0 demo的项目地址</a>，大爷有兴趣可进去看看演示，开心了就加个星)，其实却是个SPA(单页面应用)<br>没错！就是一个SPA</p>
<h3 id="作为一个SPA，当然有不同的地方"><a href="#作为一个SPA，当然有不同的地方" class="headerlink" title="作为一个SPA，当然有不同的地方"></a>作为一个SPA，当然有不同的地方</h3><p>SPA与传统网页区别的地方是SPA具有前端路由来模拟页面跳转，当然这是众多不同之一，这篇只说前端路由。<br>上一篇中有安装vue-router组件，这个就是vue的前端路由<br>vue + vue-router简直是爽，页面跳转的速度简直是不要不要的<br>不光是用户体验上的提升，作为一名开发者，在使用了如vue，react等这类MVVM框架后，就不会再想回到jQuery的时代了。</p>
<h3 id="前面搞了半天，现在要开始coding啦！"><a href="#前面搞了半天，现在要开始coding啦！" class="headerlink" title="前面搞了半天，现在要开始coding啦！"></a>前面搞了半天，现在要开始coding啦！</h3><p>好的，用自己的小编辑器打开vue项目（我用的是sublime）<br>可以看到项目目录是这样子的<br><img src="/img/vue/files-tree.png" alt="files-tree"><br>(插一句，如果喜欢这个sublime主题可以<a href="http://leenty.com/2016/10/06/sublime-material-theme/" target="_blank" rel="noopener">查看这篇文章</a>)<br>与自己的目录对比发现少几个文件，那是没有什么关系的，接下来要做的就是去创建这些文件。</p>
<h3 id="作为一个SPA，首先要有路由"><a href="#作为一个SPA，首先要有路由" class="headerlink" title="作为一个SPA，首先要有路由"></a>作为一个SPA，首先要有路由</h3><p>从目录图片里可以看到<code>main.js</code>这个文件，没错这个就是程序的入口<br>这个文件的内容是这样的<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> router <span class="keyword">from</span> <span class="string">'./router'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> App <span class="keyword">from</span> <span class="string">'./App'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* eslint-disable no-new */</span></span><br><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  router,</span><br><span class="line">  render: <span class="function"><span class="params">h</span> =&gt;</span> h(App)</span><br><span class="line">&#125;).$mount(<span class="string">'#app'</span>)</span><br></pre></td></tr></table></figure></p>
<p><a href="https://github.com/leenty/vue2/blob/master/src/main.js" target="_blank" rel="noopener"><code>main.js</code>地址</a><br>这里用的是ES6的语法，使用<code>import</code>来导入包<br>这里导入了vue包，还有两个文件，分别是<code>router.js</code>和<code>App.vue</code><br><code>.js</code>后缀是可以省略的(毕竟是亲生的，你不说导入什么类型的文件，肯定是自家人毕竟亲呀)<br>其实<code>.vue</code>后缀也是可以省略的，我建议还是写一下，如果遇到两个同名文件就尴尬了。</p>
<p>好的，这个<code>router.js</code>就是路由的输出口啦，<br><code>App.vue</code>就是目录里已经存在的那个模板文件啦，你的界面就从这里开始啦。<br>引入了包就可以开始设置路由和挂载模板了</p>
<p>顺带一提，可以看到在<code>new Vue()</code>时传入了一个对象，但是这个对象却不是键值对，<br>是这样，这是ES6的一种语法，当引用的变量名和键名相同时，就可以简写成这样<br>如果还原来是这样的<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  router: router,</span><br><span class="line">  render: <span class="function"><span class="params">h</span> =&gt;</span> h(App)</span><br><span class="line">&#125;).$mount(<span class="string">'app'</span>)</span><br><span class="line"><span class="comment">// 被简写成了</span></span><br><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  router, <span class="comment">// 这是ES6对象的简写，扩展开就是router: router</span></span><br><span class="line">  <span class="comment">// 箭头函数(=&gt;)是ES6的新语法</span></span><br><span class="line">  render: <span class="function"><span class="params">h</span> =&gt;</span> h(App) <span class="comment">// 这里扩展开就是render: (h) =&gt; &#123; return h(App) &#125;</span></span><br><span class="line">&#125;).$mount(<span class="string">'app'</span>)</span><br></pre></td></tr></table></figure></p>
<p>PS：ES6的新语法现在网上文章已经有很多了，我之后也会发一版常用的语法</p>
<h3 id="那么现在在src目录下创建router-js文件"><a href="#那么现在在src目录下创建router-js文件" class="headerlink" title="那么现在在src目录下创建router.js文件"></a>那么现在在src目录下创建<code>router.js</code>文件</h3><p>内容是这样的：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> VueRouter <span class="keyword">from</span> <span class="string">'vue-router'</span></span><br><span class="line"><span class="keyword">import</span> routes <span class="keyword">from</span> <span class="string">'./routes'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 告诉vue要使用router</span></span><br><span class="line">Vue.use(VueRouter)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* eslint-disable no-new */</span></span><br><span class="line"><span class="comment">// 实例化router对象</span></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  mode: <span class="string">'hash'</span>, <span class="comment">// 设置路由模式 可选值: "hash" | "history" | "abstract"，默认"hash"</span></span><br><span class="line">  linkActiveClass: <span class="string">'u-link--Active'</span>, <span class="comment">// 这是链接激活时的class</span></span><br><span class="line">  <span class="comment">// base: '/app/', // 这个是设置根目录路径，一般用不到，默认'/'</span></span><br><span class="line">  routes <span class="comment">// 挂载路由集合 后面会说</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 导出router对象</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> router</span><br></pre></td></tr></table></figure></p>
<p><a href="https://github.com/leenty/vue2/blob/master/src/router.js" target="_blank" rel="noopener">这是<code>router.js</code>地址</a><br>这里引入了两个包<code>vue</code>,<code>vue-router</code>和一个包含路由集合的<code>routes.js</code>文件<br>整个文件的逻辑就是，使用<code>Vue.use()</code>方法告诉vue我们使用了路由<br>然后就大大方方的导出路由对象<br><img src="/img/vue/router-main.js.png" alt="main.js router"><br>这个时候<code>main.js</code>里就可以接受到这里导出的路由对象，并挂载到vue对象上</p>
<h3 id="在src目录下创建routes-js文件"><a href="#在src目录下创建routes-js文件" class="headerlink" title="在src目录下创建routes.js文件"></a>在src目录下创建<code>routes.js</code>文件</h3><p><code>routes.js</code>是用来放置路由集合的文件<br>其实路由集合是可以写在<code>router.js</code>里的，这里为什么不写在一起呢？<br>因为当路由集合变得庞大时，如果还是写在<code>router.js</code>里，就会显得拥挤，不便于阅读<br>所以这里推荐单独写出来。<br>同时呢也可以创建路由所对应的模板文件(<code>.vue</code>文件，我把它称为模板文件)，<code>Article.vue</code>和<code>Home.vue</code><br>模板文件叫什么名由自己决定，于是就能看到这张图里所有文件都齐了<br><img src="/img/vue/files-tree.png" alt="files-tree"></p>
<p>那么在编写<code>routes.js</code>文件之前，需要先写好两个模板的内容(不然一会有没有成功都不清楚了，23333)</p>
<p>好的，贴一下<code>home.vue</code>的内容<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span> <span class="attr">lang</span>=<span class="string">"pug"</span>&gt;</span></span><br><span class="line">.home</span><br><span class="line">  h1.l-ta--c Material Desgin</span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">    data () &#123;</span><br><span class="line"><span class="javascript">      <span class="keyword">return</span> &#123;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">lang</span>=<span class="string">"stylus"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>vue模板是html结构的，这也是对界面编写最友好的方式<br>里面的<code>&lt;template&gt; &lt;/template&gt;</code>标签就是视图<br><code>&lt;script&gt;&lt;/script&gt;</code>就是js，这个没有争议<br><code>&lt;style&gt;&lt;/style&gt;</code>是写css的，这个也没有问题<br>但是当仔细看我的代码，发现里面html使用了pug，css使用了stylus<br>其实不用他们也是可行的，只是用pug和stylus写结构比较清晰<br>不用也可以的<br>如果要使用，请打开你的终端，给项目添加几个包<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i pug stylus stylus-loader -D</span><br></pre></td></tr></table></figure></p>
<p>里面的css的class(<code>.l-ta--c</code>)看着有点懵逼的，可以看看<a href="http://www.leenty.com/2016/11/06/css/#main" target="_blank" rel="noopener">使用BEM+emmet的css书写与命名技巧</a><br>好的，模板不需要太复杂，只要有字能显示就好了，至于<code>Article.vue</code>也是一样的，这里就不贴了</p>
<p>Tips：模板里推荐有一个根元素，就像这里的<code>.home</code>就是根元素，这样不容易混乱，结构会清晰</p>
<h3 id="写好了模板就可以开始编写routes-js了"><a href="#写好了模板就可以开始编写routes-js了" class="headerlink" title="写好了模板就可以开始编写routes.js了"></a>写好了模板就可以开始编写<code>routes.js</code>了</h3><p>先贴代码!<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入之前写好的两个模板</span></span><br><span class="line"><span class="keyword">import</span> Home <span class="keyword">from</span> <span class="string">'./components/Home.vue'</span></span><br><span class="line"><span class="keyword">import</span> Article <span class="keyword">from</span> <span class="string">'./components/Article.vue'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 编写路由集合</span></span><br><span class="line"><span class="keyword">const</span> routes = [</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Home'</span>, <span class="comment">// 路由名，这个字段是可选的</span></span><br><span class="line">    path: <span class="string">'/'</span>, <span class="comment">// 路由路径，这里是根路径所以是'/'</span></span><br><span class="line">    component: Home <span class="comment">// 模板</span></span><br><span class="line">  &#125;, <span class="comment">// 这些是常用的</span></span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Article'</span>,</span><br><span class="line">    path: <span class="string">'/article'</span>,</span><br><span class="line">    component: Article</span><br><span class="line">  &#125;</span><br><span class="line">]</span><br><span class="line"><span class="comment">// 导出路由集合</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> routes</span><br></pre></td></tr></table></figure></p>
<p><a href="https://github.com/leenty/vue2/blob/master/src/routes.js" target="_blank" rel="noopener">然后是文件地址</a><br>最后导出了路由集合(<code>routes</code>)后就可以在<code>router.js</code>里使用了<br>于是，前面的<code>router.js</code>里的<code>routes</code>就有了。</p>
<h3 id="现在进行最后一步，到App-vue里添加路由"><a href="#现在进行最后一步，到App-vue里添加路由" class="headerlink" title="现在进行最后一步，到App.vue里添加路由"></a>现在进行最后一步，到<code>App.vue</code>里添加路由</h3><p>代码如下：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span> <span class="attr">lang</span>=<span class="string">"pug"</span>&gt;</span></span><br><span class="line">  .app</span><br><span class="line">    header</span><br><span class="line">      //- 制作一个跳转链接</span><br><span class="line">      //- 这里不要直接用a链接跳转，那样会导致页面重载，</span><br><span class="line">      //- 相比之下用router-link是高效的方案</span><br><span class="line">      //- to属性就是链接的地址啦</span><br><span class="line">      router-link(to="/") home</span><br><span class="line">      router-link(to="/article") article</span><br><span class="line">    bodyer</span><br><span class="line">      //- 路由地址所对应的模板将会被挂载到router-view标签上</span><br><span class="line">      router-view</span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">    data () &#123;</span><br><span class="line"><span class="javascript">      <span class="keyword">return</span> &#123;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">lang</span>=<span class="string">"stylus"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p><a href="https://github.com/leenty/vue2/blob/master/src/App.vue" target="_blank" rel="noopener">地址</a><br>好了，到此为止就完成了路由搭建与使用了。</p>

      
    </div>
    <div class="article-info article-info-index">
      
      <a href="/2016/11/20/vue2-2/" class="archive-article-date">
  	<time datetime="2016-11-20T15:41:16.000Z" itemprop="datePublished"><i class="icon-clock"></i>2016-11-20</time>
</a>
      
	<div class="article-tag tagcloud">
		<i class="icon-price-tags"></i>
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vue-router/">vue-router</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuejs/">vuejs</a></li></ul>
	</div>

      

      <div class="clearfix"></div>
    </div>
  </div>
</article>










  
  
    <nav id="page-nav">
      <span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><a class="page-number" href="/page/3/">3</a><a class="page-number" href="/page/4/">4</a><a class="extend next" rel="next" href="/page/2/">Next &raquo;</a>
    </nav>
  


      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2019 leenty
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    <script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: false,
		animate: true,
		isHome: true,
		isPost: false,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false,
		root: "/",
		innerArchive: true
	}
</script>

<script src="/./main.js"></script>


    
<div class="tools-col">
  <ul class="btn-wrap">
    
      <li class="chose" data-hook="tools-section-all"><span class="text">全部</span><i class="icon-book"></i></li>
    
    
      <li data-hook="tools-section-tag"><span class="text">标签</span><i class="icon-price-tags"></i></li>
    
    
      <li data-hook="tools-section-friends"><span class="text">友链</span><i class="icon-link"></i></li>
    
    
      <li data-hook="tools-section-me"><span class="text">我</span><i class="icon-smile"></i></li>
    
  </ul>
  <div class="tools-wrap">
    
    	<section class="tools-section tools-section-all chose">
    	</section>
    

    
    	<section class="tools-section tools-section-tag">
    			<div class="widget tagcloud" id="js-tagcloud">
    				<a href="/tags/ES6/" style="font-size: 10px;">ES6</a> <a href="/tags/css/" style="font-size: 15px;">css</a> <a href="/tags/git/" style="font-size: 10px;">git</a> <a href="/tags/github/" style="font-size: 10px;">github</a> <a href="/tags/gulp/" style="font-size: 10px;">gulp</a> <a href="/tags/hexo/" style="font-size: 12.5px;">hexo</a> <a href="/tags/js/" style="font-size: 12.5px;">js</a> <a href="/tags/other/" style="font-size: 10px;">other</a> <a href="/tags/sublime/" style="font-size: 10px;">sublime</a> <a href="/tags/vim/" style="font-size: 10px;">vim</a> <a href="/tags/vue-router/" style="font-size: 17.5px;">vue-router</a> <a href="/tags/vuejs/" style="font-size: 20px;">vuejs</a> <a href="/tags/vuex/" style="font-size: 12.5px;">vuex</a>
    			</div>
    	</section>
    

    
    	<section class="tools-section tools-section-friends">
  		
  			<div class="friends-wrap" id="js-friends">
  			
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="http://vue2.leenty.com">vue2.0演示地址</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.leenty.com/">leenty的博客</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="https://whqet.github.io/">whqet的博客</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="https://shenyubin.github.io/">沈雨彬的博客</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.deboy.cn">Deboy的博客</a>
  	        
  	        </div>
  		
    	</section>
    

    
    	<section class="tools-section tools-section-me">
  	  	
  	  		<div class="aboutme-wrap" id="js-aboutme">不会捣(xia)鼓(gao)的前端不是好全栈</div>
  	  	
    	</section>
    
  </div>
  
</div>
    <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>
  </div>
</body>
</html>